package com.zbkj.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.admin.dao.ShippingTemplatesNoSendDao;
import com.zbkj.admin.dao.ShippingTemplatesNoSendDao;
import com.zbkj.admin.model.express.ShippingTemplatesFree;
import com.zbkj.admin.model.express.ShippingTemplatesNoSend;
import com.zbkj.admin.model.express.ShippingTemplatesNoSend;
import com.zbkj.admin.request.ShippingTemplatesNoSendRequest;
import com.zbkj.admin.response.ShippingTemplatesNoSendResponse;
import com.zbkj.admin.service.ShippingTemplatesNoSendService;
import com.zbkj.admin.util.CrmebUtil;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ShippingTemplatesNoSendServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class ShippingTemplatesNoSendServiceImpl extends ServiceImpl<ShippingTemplatesNoSendDao, ShippingTemplatesNoSend> implements ShippingTemplatesNoSendService {

    @Resource
    private ShippingTemplatesNoSendDao dao;

    /**
     * 保存配送区域
     *
     * @param shippingTemplatesNoSendRequestList List<ShippingTemplatesNoSendRequest> 运费集合
     * @param type                             Integer 计费方式
     * @param tempId                           Integer 运费模板id
     */
    @Override
    public Boolean saveAll(List<ShippingTemplatesNoSendRequest> shippingTemplatesNoSendRequestList, Integer type, Integer tempId) {
        ArrayList<ShippingTemplatesNoSend> shippingTemplatesNoSendsList = new ArrayList<>();
        for (ShippingTemplatesNoSendRequest shippingTemplatesNoSendRequest : shippingTemplatesNoSendRequestList) {
            String uniqueKey = DigestUtils.md5Hex(shippingTemplatesNoSendRequest.toString());
            List<String> titleArray = JSONArray.parseArray(shippingTemplatesNoSendRequest.getTitle(), String.class);
            if (shippingTemplatesNoSendRequest.getCityId().equals("all") || shippingTemplatesNoSendRequest.getCityId().equals("0")) {
                ShippingTemplatesNoSend shippingTemplatesNoSend = new ShippingTemplatesNoSend();
                shippingTemplatesNoSend.setCityId(0);
                shippingTemplatesNoSend.setTitle(titleArray.get(0));
                shippingTemplatesNoSend.setTempId(tempId);
                shippingTemplatesNoSend.setUniqid(uniqueKey);
                shippingTemplatesNoSendsList.add(shippingTemplatesNoSend);
            } else {
                List<Integer> cityIdList = CrmebUtil.stringToArray(shippingTemplatesNoSendRequest.getCityId());
                Map<Integer, String> cityMap = new HashMap<>();
                titleArray.forEach(e -> {
                    JSONArray parseArray = JSONArray.parseArray(e);
                    Integer cityId = parseArray.getInteger(2);
                    cityMap.put(cityId, e);
                });
                for (Integer cityId : cityIdList) {
                    ShippingTemplatesNoSend shippingTemplatesNoSend = new ShippingTemplatesNoSend();
                    shippingTemplatesNoSend.setCityId(cityId);
                    shippingTemplatesNoSend.setTitle(cityMap.get(cityId));
                    shippingTemplatesNoSend.setUniqid(uniqueKey);
                    shippingTemplatesNoSend.setTempId(tempId);
                    shippingTemplatesNoSendsList.add(shippingTemplatesNoSend);
                }
            }
        }
        //批量保存模板数据
        return saveBatch(shippingTemplatesNoSendsList);
    }

    /**
     * 删除模板下的无效数据
     *
     * @param tempId Integer 运费模板id
     */
    @Override
    public Boolean deleteByTempId(Integer tempId) {
        LambdaUpdateWrapper<ShippingTemplatesNoSend> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ShippingTemplatesNoSend::getTempId, tempId);
        return dao.delete(wrapper) > 0;
    }

    /**
     * 根据模板编号、城市ID查询
     *
     * @param tempId 模板编号
     * @param cityId 城市ID
     * @return 运费模板
     */
    @Override
    public ShippingTemplatesNoSend getByTempIdAndCityId(Integer tempId, Integer cityId) {
        LambdaQueryWrapper<ShippingTemplatesNoSend> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShippingTemplatesNoSend::getTempId, tempId);
        lqw.eq(ShippingTemplatesNoSend::getCityId, cityId);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

    /**
     * 是否存在区域id使用
     * @param regionId 区域id
     * @return Boolean
     */
    @Override
    public Boolean existCityId(Integer regionId) {
        LambdaQueryWrapper<ShippingTemplatesNoSend> lqw = new LambdaQueryWrapper<>();
        lqw.select(ShippingTemplatesNoSend::getId);
        lqw.eq(ShippingTemplatesNoSend::getCityId, regionId);
        lqw.last(" limit 1");
        ShippingTemplatesNoSend shippingTemplatesRegion = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(shippingTemplatesRegion);
    }

    /**
     * 分组查询
     *
     * @param tempId Integer 运费模板id
     * @return List<ShippingTemplatesNoSendRequest>
     */
    @Override
    public List<ShippingTemplatesNoSendResponse> getListGroup(Integer tempId) {
        LambdaQueryWrapper<ShippingTemplatesNoSend> lqw = Wrappers.lambdaQuery();
        lqw.select(ShippingTemplatesNoSend::getTitle,ShippingTemplatesNoSend::getUniqid);
        lqw.eq(ShippingTemplatesNoSend::getTempId, tempId);
        List<ShippingTemplatesNoSend> list = dao.selectList(lqw);
        List<ShippingTemplatesNoSendResponse> responseList = CollUtil.newArrayList();
        if (CollUtil.isEmpty(list)) {
            return responseList;
        }
        Map<String, List<ShippingTemplatesNoSend>> listMap = list.stream().collect(Collectors.groupingBy(ShippingTemplatesNoSend::getUniqid));
        Set<Map.Entry<String, List<ShippingTemplatesNoSend>>> entrySet = listMap.entrySet();
        for (Map.Entry<String, List<ShippingTemplatesNoSend>> entry : entrySet) {
            String uniqid = entry.getKey();
            String title = entry.getValue().stream().map(ShippingTemplatesNoSend::getTitle).collect(Collectors.joining(","));
            ShippingTemplatesNoSend free = entry.getValue().get(0);
            ShippingTemplatesNoSendResponse response = new ShippingTemplatesNoSendResponse();
            response.setTitle(title);
            response.setUniqid(uniqid);
            responseList.add(response);
        }
        return responseList;
    }
}

